<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of comunas_model
 *
 * @author daniel
 */
class Comunas_model extends Model {

	private $tableName;

	public function __construct() {
		parent::__construct();

		$this->load->database();
		$this->tableName = "comunas";

		$this->pagination_enabled = FALSE;
		$this->pagination_per_page = $this->config->item("mantenedor_comunas_per_page");
		$this->pagination_num_links = 5;
		$this->pager = '';

		/**
		 *    bool $this->raw_data		
		 *    Used to decide what data should the SQL queries retrieve if tables are joined
		 *     - TRUE:  just the field names of the comunas table
		 *     - FALSE: related fields are replaced with the forign tables values
		 *    Triggered to TRUE in the controller/edit method		 
		 */
		$this->raw_data = FALSE;
	}

	/* retorna un array con todas las regiones que estan en la tabla comunas */

	public function obtener_todas_las_regiones() {
		$this->db->distinct();
		$this->db->select("region");
		$query = $this->db->get($this->tableName);

		$regiones = array();

		foreach ($query->result() as $row) {
			$regiones[] = $row->region;
		}

		return $regiones;
	}

	/* retorna todas las comunas de la base de datos */

	public function obtener_todas() {
		return $this->db->get($this->tableName);
	}

	/**
	 * retorna un array con cada comuna
	 * como un elemento del array.
	 *
	 * por ejemplo:
	 *
	 * array (
	 * 	"comuna1", "comuna2", "comuna3", etc...
	 * )
	 *
	 * @return <type>
	 */
	public function listado_en_array_simple($region = '') {
		if (!empty($region)) {
			$this->db->where('region', $region);
		}

		$query = $this->db->get($this->tableName);

		$results = array();

		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$results[] = $row->nombre;
			}
		}

		return $results;
	}

	/**
	 * retorna un array con cada comuna
	 * como un elemento del array, ademas cada comuna tambien es la llave
	 *
	 * ej:
	 *
	 * array(
	 * 	"comuna1" => "comuna1",
	 * 	"comuna2" => "comuna2",
	 * 	"comuna3" => "comuna3"
	 * )
	 *
	 * @return <type>
	 */
	function listado_en_array_doble($region = '') {
		if (!empty($region)) {
			$this->db->where('region', $region);
		}

		$this->db->orderby('nombre', 'asc');
		$query = $this->db->get($this->tableName);

		$results = array();

		if ($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				$results[$row->nombre] = $row->nombre;
			}
		}

		return $results;
	}

	function get($id, $get_one = false) {

		$select_statement = ( $this->raw_data ) ? 'region,nombre' : 'region,nombre';
		$this->db->select($select_statement);
		$this->db->from('comunas');


		// Pick one record
		// Field order sample may be empty because no record is requested, eg. create/GET event
		if ($get_one) {
			$this->db->limit(1, 0);
		} else { // Select the desired record {
			$this->db->where('region', $id);
		}

		$query = $this->db->get();

		if ($query->num_rows() > 0) {
			$row = $query->row_array();
			return array(
				'region' => $row['region'],
				'nombre' => $row['nombre'],
			);
		} else {
			return array();
		}
	}

	function insert($data) {
		$this->db->insert('comunas', $data);
		return $this->db->insert_id();
	}

	function update($id, $data) {
		$this->db->where('region', $id);
		$this->db->update('comunas', $data);
	}

	function delete($region, $comuna) {
		$where["region"] = $region;
		$where["nombre"] = $comuna;

		$this->db->where($where);
		$this->db->delete($this->tableName);
	}

	function lister($page = FALSE) {

		$this->db->start_cache();
		$this->db->select('region,nombre');
		$this->db->from('comunas');
		//$this->db->order_by( '', 'ASC' );


		/**
		 *   PAGINATION
		 */
		if ($this->pagination_enabled == TRUE) {
			$config = array();
			$config['total_rows'] = $this->db->count_all_results('comunas');
			//$config['base_url']    = '/comunas/index/';
			$config['base_url'] = base_url() . index_page() . '/comunas/index/';
			$config['uri_segment'] = 3;
			$config['per_page'] = $this->pagination_per_page;
			$config['num_links'] = $this->pagination_num_links;

			$this->load->library('pagination');
			$this->pagination->initialize($config);
			$this->pager = $this->pagination->create_links();

			$this->db->limit($config['per_page'], $page);
		}

		// Get the results
		$query = $this->db->get();

		$temp_result = array();

		foreach ($query->result_array() as $row) {
			$temp_result[] = array(
				'region' => $row['region'],
				'nombre' => $row['nombre'],
			);
		}
		$this->db->flush_cache();
		return $temp_result;
	}

	function search($keyword, $page = FALSE) {
		$meta = $this->metadata();
		$this->db->start_cache();
		$this->db->select('region,nombre');
		$this->db->from('comunas');


		// Delete this line after setting up the search conditions
		die('Please see models/model_comunas.php for setting up the search method.');

		/**
		 *  Rename field_name_to_search to the field you wish to search
		 *  or create advanced search conditions here
		 */
		$this->db->where('field_name_to_search LIKE "%' . $keyword . '%"');

		/**
		 *   PAGINATION
		 */
		if ($this->pagination_enabled == TRUE) {
			$config = array();
			$config['total_rows'] = $this->db->count_all_results('comunas');
			$config['base_url'] = '/comunas/search/' . $keyword . '/';
			$config['uri_segment'] = 4;
			$config['per_page'] = $this->pagination_per_page;
			$config['num_links'] = $this->pagination_num_links;

			$this->load->library('pagination');
			$this->pagination->initialize($config);
			$this->pager = $this->pagination->create_links();

			$this->db->limit($config['per_page'], $page);
		}

		$query = $this->db->get();

		$temp_result = array();

		foreach ($query->result_array() as $row) {
			$temp_result[] = array(
				'region' => $row['region'],
				'nombre' => $row['nombre'],
			);
		}
		$this->db->flush_cache();
		return $temp_result;
	}

	/**
	 *  Some utility methods
	 */
	function fields($withID = FALSE) {
		$fs = array(
			'region' => lang('region'),
			'nombre' => lang('nombre')
		);

		if ($withID == FALSE) {
			unset($fs[0]);
		}
		return $fs;
	}

	function pagination($bool) {
		$this->pagination_enabled = ( $bool === TRUE ) ? TRUE : FALSE;
	}

	/**
	 *  Parses the table data and look for enum values, to match them with language variables
	 */
	function metadata() {
		$this->load->library('explain_table');

		$metadata = $this->explain_table->parse('comunas');

		foreach ($metadata as $k => $md) {
			if (!empty($md['enum_values'])) {
				$metadata[$k]['enum_names'] = array_map('lang', $md['enum_values']);
			}
		}
		return $metadata;
	}

}
